<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 卡片上部 -->
      <el-row :gutter="20">
        <!-- input框 -->
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUserInfo">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table :data="users" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 删除 设置 按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editUserInfo(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteUserInfo(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                @click="showSetRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[4, 8, 12]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="用户新申请"
        :visible.sync="userDialogVisible"
        width="50%"
        @close="closeAddDialog"
      >
        <!-- 表单 -->
        <el-form
          :model="addUser"
          :rules="addUserRules"
          ref="addUserRef"
          label-width="100px"
        >
          <el-form-item label="用户名：" prop="username">
            <el-input v-model="addUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="addUser.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="addUser.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号码：" prop="mobile">
            <el-input v-model="addUser.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改数据对话框 -->
      <el-dialog
        title="修改用户数据"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="closEditDialog"
      >
        <!-- 表单 -->
        <el-form
          :model="editUser"
          :rules="editUserRules"
          ref="editUserRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名:">
            <el-input v-model="editUser.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="editUser.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号:" prop="mobile">
            <el-input v-model="editUser.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 删除用户对话框 -->
      <el-dialog
        title="删除用户"
        :visible.sync="deleteDialogVisible"
        width="30%"
      >
        <span>是否删除数据</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteUserData()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        @close="closeRole"
      >
        <div>
          <p>当前的用户：{{ setRole.username }}</p>
          <p>当前的角色：{{ setRole.role_name }}</p>
          <el-select v-model="setRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoleData">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱的规则
    var emailValidate = (rule, value, callback) => {
      const exp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (exp.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱!'))
    }
    // 验证手机号码规则
    var mobileValidate = (rule, value, callback) => {
      const exp =
        /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/

      if (exp.test(value)) {
        return callback()
      }
      callback(new Error('手机号格式错误'))
    }

    return {
      // 查询信息
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4,
      },
      total: 0,
      users: [],

      // 修改数据对话框是否开启
      editDialogVisible: false,
      // 修改用户的数据
      editUser: {},
      // 修改用户的规则
      editUserRules: {
        email: [
          { required: true, message: '请输入email', trigger: 'blur' },
          { validator: emailValidate, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入mobile', trigger: 'blur' },
          { validator: mobileValidate, trigger: 'blur' },
        ],
      },

      // 新增用户对话框是否开启
      userDialogVisible: false,
      // 新增用户
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 新增用户核对规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailValidate, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: mobileValidate, trigger: 'blur' },
        ],
      },

      // 是否显示删除对话框
      deleteDialogVisible: false,
      // 需要删除的用户id
      deleteId: '',

      // 修改角色的信息
      setRole: {},
      // 是否开启分配角色的对话框
      setRoleDialogVisible: false,
      // 角色列表
      rolesList: [],
      // 当前选中的角色的id
      setRoleId: '',
      // 当前选中的角色名称
      setRoleName: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户数据列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (!res) return this.$message.error('获取管理员列表失败')

      this.total = res.data.total
      this.users = res.data.users
    },
    // 处理 页面显示条数大小事件
    handleSizeChange(sizeChange) {
      // 更新页面显示条数
      this.queryInfo.pagesize = sizeChange
      // 重新请求数据
      this.getUserList()
    },
    // 处理 当前页变动时候触发的事件
    handleCurrentChange(currentChange) {
      // 更新页码
      this.queryInfo.pagenum = currentChange
      // 重新请求数据
      this.getUserList()
    },
    // 用户状态改变
    async userStateChange(userInfo) {
      // 请求改变数据
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )

      // 判断是否请求成功  如果失败则还原之前的状态
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('设置状态失败')
      }

      this.$message.success('设置状态成功')
    },

    // 获取要修改用户数据
    editUserInfo(userInfo) {
      // 打开会话框
      this.editDialogVisible = true
      // 获取相关数据
      this.editUser = {
        id: userInfo.id,
        username: userInfo.username,
        email: userInfo.email,
        mobile: userInfo.mobile,
      }
    },
    // 关闭修改对话框  重置对话框内容
    closEditDialog() {
      this.$refs.editUserRef.resetFields()
    },
    // 修改数据
    editUserData() {
      this.$refs.editUserRef.validate(async (valid) => {
        if (!valid) return
        // 数据格式输入都正确  则连接数据库 更新数据
        const { data: res } = await this.$http.put(
          'users/' + this.editUser.id,
          {
            email: this.editUser.email,
            mobile: this.editUser.mobile,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取用户信息失败')
        }
        // 修改成功后
        this.$message.success('获取用户信息成功')
        this.editDialogVisible = false
        // 重新获取数据
        this.getUserList()
      })
    },

    // 添加用户的信息
    addUserInfo() {
      // 开启对话框  填写数据
      this.userDialogVisible = true
    },
    // 关闭添加对话框  重置对话框内容
    closeAddDialog() {
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户到数据库
    addUserData() {
      // 核对格式无误 发送请求
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return

        // 发送请求
        const { data: res } = await this.$http.post('users', this.addUser)
        if (res.meta.status !== 201) return this.$message.error('创建失败')

        // 添加成功
        this.$message.success('创建成功')
        this.userDialogVisible = false
        this.getUserList()
      })
    },

    // 删除用户的信息
    deleteUserInfo(id) {
      this.deleteDialogVisible = true
      this.deleteId = id
    },
    // 删除用户
    async deleteUserData() {
      const { data: res } = await this.$http.delete('users/' + this.deleteId)

      if (res.meta.status !== 200) return this.$message.error('删除失败')
      // 删除成功
      this.$message.success('删除成功')
      this.deleteDialogVisible = false
      this.getUserList()
    },

    // 开启分配角色对话框
    async showSetRole(scope) {
      this.setRole = scope
      // 获取后台角色数据

      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) THIS.$message.error('获取角色列表失败')

      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 修改角色信息
    async setRoleData() {
      const { data: res } = await this.$http.put(
        `users/${this.setRole.id}/role`,
        {
          rid: this.setRoleId,
        }
      )
      if (res.meta.status !== 200) this.$message.error('修改角色失败')

      this.setRoleDialogVisible = false
      this.$message.success('修改角色成功')
      this.getUserList()
    },
    //关闭修改角色
    closeRole() {
      this.setRoleId = ''
      this.setRole = {}
    },
  },
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
</style>